<template>
<div class="home-box" style="height:100%;overflow:hidden">
	<div class="container">
		<div class="left">
			<!-- <div class="customLeftStyle_cover" v-if="PathAndTime && CompareTime"></div> -->
			<div class="style-components"
				:class="getStyleComponentsState === 'hide' ? 'style-components-active' : ''"
				:style="getStyleComponentsCoverState ? 'z-index: 2;' : ''">
				<div :class="getStyleComponentsState === 'show' ? '' : 'style-components-content-active'" >
					<p class="style-components-title">组件分类</p>
					<module-name></module-name>
				</div>
				<!-- 用来hover显示抽屉的div -->
				<div class="style-components-hover"
					v-show="getStyleComponentsState === 'hide'"
					@mouseover="showStyleComponents">
					<img src="static/image/style-components-hover.png" />
					<span class="text">组件列表</span>
				</div>
			</div>
		</div>
		<!-- 当抽屉出来的时候，有个遮罩 -->
		<div class="style-components-cover"
			v-show="getStyleComponentsCoverState"
			@click.stop="click2hideStyleComponents"
			:style="`width: ${getWidth()}px; height: ${getHeight()}px`">
		</div>

		<div class="mid">
			<div class="customMidStyle_cover" v-if="(PathAndTime && isShowInfoInfo) || !showTips"></div>
			<div class="screen-container">
				<div class="screen-content">
					<router-view name="real"></router-view>
				</div>
			</div>
		</div>
		<div class="right"  :class=" ((PathAndTime && isShowInfoInfo) || !showTips)  ? 'slideEgiht' : ''">
			<div style="background-color: #fff;margin-bottom: 20px;padding: 20px;text-align: left;">
				<div class="righttop">
					<!-- <span>下拉选择跳转的活动页面</span>
					<select class="searchselect" v-model="selected">
						<option v-for="(path, index) in paths" :key="index" :value="path.routerName">{{path.pageName}}</option>
					</select> -->
				</div>
				<div class="currentStoreName">
					<span class="storeNameTitle">当前门店:</span><span>{{getStoreName}}</span>
				</div>
				<div class="immediatePublish" v-if="isPageNameHome">
					<span @click="immediatePublish">立即发布</span>
				</div>
				<div class="intervalPublish" v-if="isPageNameHome && isShowInterFabu">
					<span @click="intervalPublish">定时发布</span>
				</div>
				<!-- 操作按钮 -->
				<div class="handle-button" style="display: inline-block;float: right;">
					<blue-button :clickEvent="save"></blue-button>
					<!-- <back-home style="margin-left: 15px;" :clickEvent="backHomeClickEvent"></back-home> -->
				</div>
			</div>
			<div class="interVal-info clearfix" v-if="(PathAndTime && isShowInfoInfo) || !showTips">
				<div class="left-info">
					<div>该页面将在<span>{{DataInterval(showTime)}}</span>发布到线上</div>
					<div><span class="tips">温馨提示:亲，由于您的页面设置了定时发布,如需编辑模块，请先取消定时发布</span></div>
				</div>
				<div class="right-info"><span class="quxiaoPublish" @click="clickCanclePublish">取消定时发布</span></div>
			</div>
			<div style="background-color: #fff;height: 550px;padding: 20px;border: 1px solid #ddd">
				<router-view name="edit" style="overflow-y: scroll;height: 510px"></router-view>
			</div>
		</div>
	</div>
	<edit-model ref="editModel" title="设置定时发布时间">
			<div class="modify-template-box slot-banner" slot="main">	
				<div style="text-align:left">
					<p class="eidt-slot-title" style="display:inline-block">
						<span class="required">*</span>发布日期
					</p>
					<el-date-picker type="datetime" v-model="publishTime" placeholder="选择日期时间" style="width: 350px;border:1px solid #eee">
					</el-date-picker>
				</div>
				<div class="tips"><span>*</span>您可以设置最近七天内的任意时间段发布页面</div>
				<div class="fabu-box">
					<blue-button text="确定" :clickEvent="confirmPublish"></blue-button>
					<blue-button text="取消" class="cancelIntervalPublish" ::clickEvent="cancelPublish"></blue-button>
				</div>
			</div>
	</edit-model>
	<m-dialog ref="dialog"></m-dialog>
	<m-toast ref="mToast"></m-toast>
</div>
</template>
<script>
	import BlueButton from "../../edit-components/BlueButton";
	import GrayButton from "../../edit-components/GrayButton";
	import moduleName from "./style.vue";
	import {mapGetters,mapMutations} from "vuex";
	import Toast from "../../edit-components/Toast";
	import {Select} from "element-ui";
	import {DRAG_START} from "../../helper/drag-plugin/event";
	import {DRAG_DROP} from "../../helper/drag-plugin/event";
	import EditModel from "../../edit-components/EditModel";
	import { DatePicker } from "element-ui";
	import Dialog from "../../edit-components/Dialog";
	import CustPageUtil from "../../edit-components/AddPage/helper/index";
	import CustPage from "../../edit-components/AddPage/Model/index";//引进实体类
	import {initEditComponentsList} from "../../helper/drag-plugin/initComponents";
	import getPageName from "../../utils/gw/getPageName"
	import initComponentsId from "../../utils/initComponentsId"
	import initLinkedList from "../../utils/settings/initLinkedList"
	import styleLoader from "../../helper/drag-plugin/css-modules";
	import editBtn from "../../helper/drag-plugin/css-modules/edit-button";
	export default {
		data() {
			return {
				selected:'',
				publishTime:'',//定时发布的时间
				isSorted: false, //默认是否排序
				showTips:true,
				isShowInfoInfo:true
			}
		},
		computed: {
			...mapGetters("gw", [
				"getSpecialTemplate",
				"getSpecialTemplateParams",
				"getRealComponentsList"
			]),
			...mapGetters([
				"getStyleComponentsState",
				"getStyleComponentsCoverState",
				"getCurrentTemplate",
			]),
			...mapGetters("lxn", [
				"getclickStoreName",
				"getInterValObj"
			]),
			getStoreName() {
				return localStorage.getItem('storeName')
			},
			PathAndTime() {
				if(getPageName()==='home') return
				let isShowInfo = this.$store.getters["gw/getSpecialTemplate"][getPageName()] || {}
				let oldPath
				if(isShowInfo.config && isShowInfo.config.id){
					oldPath = isShowInfo.config.id ||''
				}
				let oldPageInfo = this.$store.getters["gw/getSpecialTemplate"][oldPath]
				let intervalTime = ''
				if(oldPageInfo && oldPageInfo.config && oldPageInfo.config.MarkSign){
					intervalTime = oldPageInfo.config.MarkSign.time
				}
				if(new Date().getTime() < intervalTime){
					return true
				} else {
					return false
				}
			},
			//回显时间
			showTime(){
				let isShowInfo = this.$store.getters["gw/getSpecialTemplate"][getPageName()]
				let oldPath = isShowInfo.config.id
				let oldPageInfo = this.$store.getters["gw/getSpecialTemplate"][oldPath]
				return oldPageInfo.config.MarkSign.time
			},
			pageArray() {
                let pageArray = [];
                if (!this.getSpecialTemplate.config) return pageArray;
                for (let item of this.getSpecialTemplate.config.pages) {
                    let pageItem = new CustPage(item);
                    pageArray.push(pageItem);
                }
                if (this.isSorted) {
                    return pageArray;  
                } else {
                    this.isSorted = true;
                    return pageArray.sort((m, n) => {
                        let time1 = m.updateTime || m.createTime || 0;
                        let time2 = n.updateTime || n.createTime || 0;
                        return time2 - time1;
                    });
                }
			},
			isPageNameHome() {
				if (getPageName()==='home' || getPageName() === 'IntegralBuy' ||  getPageName()==='buyGiftCard'){
					return false
				} else {
					return true
				}
			},
			interValTimeAddSeven:{
				get:function(){
					let defaultEndTime = new Date().setUTCDate(new Date().getUTCDate() + 7);
					return defaultEndTime
				},
				set: function () {}
			},
			componentHeaderId(){
				let pageHeader  = this.getRealComponentsList[0][0] || [];
				let arr = []
				for(let i=0; i< pageHeader.length; i++){
					arr.push(pageHeader[i].id)
				}
				return arr
			},
			componentContentId(){
				let pageContent = this.getRealComponentsList[0][1] || [];
				let arr = []
				for(let i=0; i< pageContent.length; i++){
					arr.push(pageContent[i].id)
				}
				return arr
			},
			isShowInterFabu(){
				// this.pageArray.map((item,index)=>{
				// 	if(item.path === getPageName()){
				// 		if(item.state === 0){
				// 			return false
				// 		}else {
				// 			return true
				// 		}
				// 	}
				// });
				for(let i=0;i<this.pageArray.length;i++){
					if( this.pageArray[i].path=== getPageName()){
						if(this.pageArray[i].state === 1){
							return true
						}else {
							return false
						}
					}
				}
			}

		},
		methods: {
			...mapMutations([
			    "setCurrentTemplate",
			]),
			...mapMutations("gw",[
			    "setSpecialTemplateParams",
			]),

			DataInterval(time) {
				if(time) {
					let date = new Date(time);
					return `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()> 9 ? date.getDate() : '0' + date.getDate()}  ${date.getHours() > 9 ? date.getHours() : '0' + date.getHours()}:${date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()}`;
				} 
			},
			//保存模板更改
			save() {
				// if(!this.getCurrentTemplate.rid) return
				this.updateDomTreeToDB((data) => {
					console.log("打印data看看你是什么",data)
					this.infoToast("保存模板成功");
					let specialPage = data.find((item)=>{
						return item.tpDesc === 'specialtemplateforaddpages'
					}).tpConfig
					this.$store.commit("gw/setSpecialTemplate", JSON.parse(specialPage))
				}, () => {
					console.log("打印data看看你是什么",data)
					// this.infoToast("保存模板成功");
				});
			},
			//显示样式组件的方法
			showStyleComponents() {
				this.$store.commit("setStyleComponentsState", "show");
				this.$store.commit("setStyleComponentsCoverState", true);
			},
			//点击遮罩层就隐藏样式组件
			click2hideStyleComponents() {
				this.$store.commit("setStyleComponentsState", "hide");
				this.$store.commit("setStyleComponentsCoverState", false);
			},
			//显示Toast的方法
			infoToast(msg) {
				this.$refs.mToast.toast(msg);
			},
			//获得窗口宽度
			getWidth() {
				return window.innerWidth;
			},
			getHeight() {
				return window.innerHeight;
			},
			//当屏幕dpi小于等于1366px的时候，左侧组件列表变为抽屉式的
			resetStyleComponentsStyle() {
				if (window.innerWidth <= 1366) {
					this.$store.commit("setStyleComponentsState", "hide");
				}
			},
			//当拖拽结束的时候隐藏右侧的遮罩层
			addDragStartListener(){
				this.hanldeDragStart = () => {
					this.$store.commit("setStyleComponentsState", "hide");
					this.$store.commit("setStyleComponentsCoverState", false);
				};
				PSEvent.listen(DRAG_START, this.hanldeDragStart);
			},
			removeDragStartListener() {
				PSEvent.remove(DRAG_START, this.hanldeDragStart);
			},
			immediatePublish() {
				//此时要调用一下更新活动页面列表的方法
				this.pageArray.forEach((item,index)=>{
					if(item.path === getPageName()){
						item.setState(1)
					}
				});
				// CustPageUtil.update(this, this.pageArray);
				//替换pageArray
				window.manifest.config.pages = this.pageArray;
				// 立即发布就是保存的功能
				this.updateDomTreeToDB((data) => {
					this.infoToast("发布成功");
					let specialPage = data.find((item)=>{
						return item.tpDesc === 'specialtemplateforaddpages'
					}).tpConfig
					this.$store.commit("gw/setSpecialTemplate", JSON.parse(specialPage))
				}, () => {
					this.infoToast("发布失败");
				});
			},
			intervalPublish() {
				this.$refs.editModel.showCover();
			},
			//校验定时发布的时间(加上七天)
			checkTime(){
				let addSevenTime = this.interValTimeAddSeven
				let nowTime = new Date().getTime()
				console.log('打印',addSevenTime,nowTime)
			},
			//确认定时发布
			confirmPublish(){
				if(new Date(this.publishTime).getTime() > this.interValTimeAddSeven){
					this.$refs.mToast.toast("请选择最近七天的时间")
					return
				}
				//点击确认关闭弹窗
				this.$refs.editModel.hideCover();
				//获取新的页面和新的ID
				let result = this.createNewPage()
				console.log('打印result',result)
				//第一步：传给新页面（生成新页面）
				window.manifest[result.newPageId] = JSON.parse(JSON.stringify(window.manifest[getPageName()]));
				//第二步：推进一个新的页面进入pageArray
				let newCustPageObj = {
					id : result.newPageId,
					path :result.newPageId,
					title :result.newPageId + ' ' +'copy',
					type :'NewThematicActivities',
					createTime: new Date().getTime(),
                    updateTime: new Date().getTime(),
					state: 0,
					pageIsShow :false
				}
				this.pageArray.push(new CustPage(newCustPageObj));

 				//第三步：还原原始页面的数据
				window.manifest[getPageName()] = result.originPage;
				//给设置失效时间的页面添加标识（后续判断条件）
				//活动页中回显定时发布时间
				let MarkSign = {
					originPath:'',
					newPath:'',
					time:''
				}
				this.pageArray.forEach((item,index)=>{
					if(item.path === getPageName()){
						item.setIntervalTime(this.publishTime)
						MarkSign.originPath = getPageName();
						MarkSign.newPath = result.newPageId;
						MarkSign.time = new Date(item.intervalTime).getTime();
					}	
				});
				//替换pageArray
				window.manifest.config.pages = this.pageArray;
				//存进MarkSign
				window.manifest[getPageName()].config.MarkSign = MarkSign;
				//新页面用来存放新编辑的组件
				console.log("新写入的id", result.newPageId)
				console.log("新写入的id", window.manifest)
				this.updateDomTreeToDB((data) => {
					this.infoToast("定时发布成功");
					let specialPage = data.find((item)=>{
						return item.tpDesc === 'specialtemplateforaddpages'
					}).tpConfig
					this.$store.commit("gw/setSpecialTemplate", JSON.parse(specialPage))
				}, () => {
					this.infoToast("定时发布失败");
				});
				// let obj ={}
				// obj[getPageName()] = new Date(this.publishTime).getTime()
				// this.$store.commit("lxn/setInterValObj",obj)

			},
			//第一步生成一个新的页面的方法(页面的id要重新生成)
			createNewPage() {
				let tpConfig = {}
				let result = {
					originPage: {},//原有的页面结构
					newPageId: {}//新页面的id
				}
				// 这里相当于取的是接口里面的数据
				// 在当前页面没有保存之前是不会变的
				// 因此可以作为老页面的副本保存
				if (this.getCurrentTemplate && this.getCurrentTemplate.tpConfig) {
					tpConfig = JSON.parse(this.getCurrentTemplate.tpConfig)
				}
				for(let key in tpConfig) {
					if (key === 'config') continue;
					if (key === getPageName()) {
						result.originPage = tpConfig[key]//拿到原有页面的结构
					}
				}
				//给新的页面赋予新的id,以待备用(相当于给此页面生成一个副本)
				result.newPageId = initComponentsId();
				return result
			},
			savePathAndTime (){
				if(getPageName()==='home' || getPageName() === 'IntegralBuy'||getPageName()==='buyGiftCard'){return}
				let isShowInfo = this.$store.getters["gw/getSpecialTemplate"][getPageName()]
				let oldPath = isShowInfo.config.id
				console.log("this.pageArray",this.pageArray)
				this.pageArray.forEach((item,index)=>{
					if(item.id === oldPath){
						if(item.intervalTime === ''){
							this.isShowInfoInfo = false
						}
						
					}
				})
				
			},
			//第二步返回当前活动页面之前的页面(用于后面的合并)
			createOldPage() {
				let tpConfig = {}
				let oldTpConfig = {}
				if(this.getCurrentTemplate && this.getCurrentTemplate.tpConfig) {
					tpConfig = JSON.parse(this.getCurrentTemplate.tpConfig)
				}
				for(let key in tpConfig) {
					if (key ==='config') continue;
					if (key === getPageName()){
						oldTpConfig = tpConfig[key]
					}
				}
				return oldTpConfig
			},
			//取消按钮
			cancelPublish(){
				this.$refs.editModel.hideCover();
			},
			//取消定时发布
			clickCanclePublish() {
				let msg =`该页面将于${this.DataInterval(this.showTime)}发布到线上,您确认要取消发布嘛？`
				let confirmFn = ()=>{
					let isShowInfo = this.$store.getters["gw/getSpecialTemplate"][getPageName()]
					let oldPath = isShowInfo.config.id
					//此时定时发布时间要设置为空值
					this.pageArray.forEach((item,index)=>{
						if(item.id === oldPath){
							item.setIntervalTime("")
							this.showTips = false
						}
					})
					CustPageUtil.update(this, this.pageArray)
					//如果点击取消发布，那么现在在的页面的一定是新页面,所以需要删除新页面
					let _manifest = this.$store.getters["gw/getSpecialTemplate"] || {};
					window.manifest = initLinkedList({..._manifest});
					window.manifest[oldPath]  =  window.manifest[getPageName()]
					for (let k in window.manifest){
						if(k===getPageName()){
							delete window.manifest[getPageName()]
						}
					}
					//重新给vuex中的值赋值
					this.$store.commit("gw/setSpecialTemplate",window.manifest)
					this.$refs.mToast.toast("取消定时发布成功");
				}
				this.infoDialog(msg,confirmFn);
			},
			infoDialog(msg, confirmFn) {
				this.$refs.dialog.dialog({
					msg,
					confirmFn
				});
			},
			controlCompenentDrag(){
				let Arr = this.componentHeaderId.concat(this.componentContentId)
				for(let i = 0 ; i < Arr.length; i++){
					document.querySelector(`div[data-id=${Arr[i]}]`).setAttribute("draggable", false)
					document.querySelector(".cover-edit-btn") && (document.querySelector(".cover-edit-btn").style = styleLoader(editBtn.blue_btn_disable))
				}
			}
		},
		watch: {
			selected(routerName) {
				initEditComponentsList({componentName: ""});
				this.$router.push({
					name: "middleware",
					params:{
						routerName
					},
					query: {
						env: "edit"
					}
				})
			}
		},
		beforeRouteEnter(to,from,next){
			next()
		},
		components: {
			"blue-button": BlueButton,
			"gray-button": GrayButton,
			'moduleName': moduleName,
			"m-toast": Toast,
			"el-select":Select,
			"el-option":Option,
			"edit-model": EditModel,
			"m-dialog": Dialog,
			"el-date-picker": DatePicker,
		},
		created() {
			this.addDragStartListener();
			this.checkTime()
		},
		mounted() {
			this.savePathAndTime()
			this.resetStyleComponentsStyle()
		},
		beforeDestroy() {
			this.removeDragStartListener();
		}
	}
</script>
<style scoped>
	.container {
		display: flex;
		height: 100%;
		width: 100%;
		background: #f0f0f0;
		align-items: center;
	}
	
	.left {
		border-right: 1px solid #ddd;
		/* width: 230px; */
		height: 100%;
		background: #f1f1f1;
		overflow-y: scroll;
		z-index:10
	}
	.mid {
		position:relative;
		margin: 0 40px;
		overflow-y:auto
	}
	.screen-container {
		border: 40px solid #ddd;
		border-width: 55px 10px;
		border-radius: 40px;
		overflow: hidden;
		width: 375px;
		height: 667px;
		box-sizing: border-box;
		box-shadow: 0px 3px 0 #BBB, 0px 4px 0 #BBB, 0px 5px 0 #BBB, 0px 7px 0 #BBB, 0px 10px 20px #666;
		overflow: hidden;
	}
	
	.screen-content {
		overflow-y: auto;
		height: 100%;
		width: 100%;
	}
	
	.righttop {
		height: 30px;
		text-align: left;
		display: inline-block;
	}
	
	.right {
		flex: 1;
		min-height: 550px;
		margin-right: 20px;
		max-width: 55%;
    	overflow-x: hidden;
	}
	::-webkit-scrollbar {
		width: 0px;
		height:8px;
		background: #c1c1c1;
}
	.searchselect {
		width: 200px;
		height: 30px;
		border: 1px solid #ccc;
		display: inline-block;
		margin-left: 10px;
		border-radius: 2px;
		text-indent: 5px;
	}

	/* 用来hover显示抽屉的div */
	.style-components.style-components-active {
		margin-right: 50px;
		width: 0 !important;
	}
	.style-components-content-active {
		opacity: 0;
	}
	.style-components-hover {
		position: absolute;
		top: 45%;
		right: -31px;
		height: 150px;
		width: 30px;
		display: flex;
		align-items: center;
		cursor: pointer;
	}
	.style-components-hover img {
		position: absolute;
		left: 0;
		top: 0;
		height: 100%;
		width: 100%;
	}
	.style-components-hover span {
		display: flex;
		flex-flow: column nowrap;
		height: 100%;
		justify-content: center;
		position: relative;
		z-index: 1;
		color: #fff;
		font-size: 12px;
		padding: 5px;
	}
	.style-components-cover {
		position: fixed;
		left: 0;
		top: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 6;
	}
	.style-components-content-active {
		opacity: 0;
	}
	.style-components-title {
		color: #ff9e13;
		font-weight: bold;
		padding:15px 0;
		font-size:16px;
		background-color: #fff;
	}
	.style-components-hover {
		position: absolute;
		top: 45%;
		right: -31px;
		height: 150px;
		width: 30px;
		display: flex;
		align-items: center;
		cursor: pointer;
	}
	.style-components-hover img {
		position: absolute;
		left: 0;
		top: 0;
		height: 100%;
		width: 100%;
	}
	.style-components-hover span {
		display: flex;
		flex-flow: column nowrap;
		height: 100%;
		justify-content: center;
		position: relative;
		z-index: 1;
		color: #fff;
		font-size: 12px;
		padding: 5px;
	}
	.style-components {
		position: relative;
		border-right: 1px solid #dddddd;
		float: left;
		background: #fff;
		width: 230px;
		height: 100%;
		padding-top: 22px;
		transition: all 0.3s;
	}
	.currentStoreName,.immediatePublish,.intervalPublish,.cancleImmPublish{
		display:inline-block;
		margin-left:30px;
	}
	.immediatePublish>span,.intervalPublish>span,.cancleImmPublish>span{
		border: 1px solid rgba(22, 155, 213, 1);
    	background-color: rgba(22, 155, 213, 1);
		border-radius:4px;
		color:#fff;
		padding:3px 5px;
		cursor:pointer;
	}
	.storeNameTitle{
		margin-right:4px;
	}
	.cancelIntervalPublish{
		margin-left:50px
	}
	.tips{
		color:#9a9a9a;
		margin-top:25px;
		text-align:left
	}
	.clearfix:after {
		content:""; 
		display: block; 
		clear:both; 
		}
	.interVal-info{
		background-color: #fff;
		text-align: left;
		margin-bottom:15px;
		padding:5px;
	}
	.tips{
		color:#999;
	}
	.left-info{
		float:left
	}
	.right-info{
		float:right;
		margin-top:10px;
		border:1px solid blue;
		margin-right:10px;
		padding:4px;
		border-radius:4px;
		color:blue

	}
	.customLeftStyle_cover {
		height: 100%;
		width: 230px;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 6;
	}
	.customMidStyle_cover{
		height: 100%;
		width: 100%;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 6;
		
	}
	.slideEgiht{
		margin-top:80px;
	}
</style>